<!-- src/views/About.vue -->
<template>
  <div>
    <h1>Config SQL Server Adapter</h1>

    <!-- 创建查询语句 -->
    <!-- 规则1：SQL，save，active,method,params,url-->
    <!-- select columns from tables where columns 条件 value or 子查询（）-->
    <el-form :model="form" label-width="120px">
      <!-- 列名称 -->
      <el-form-item label="列名称">
        <el-select
          v-model="selectTableColumns"
          class="m-2"
          placeholder="Select Table Columns"
          size="large"
          multiple
        >
          <el-option
            v-for="item in tableColumns"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 表名 -->
      <el-form-item label="表名称">
        <el-select
          v-model="selectTable"
          class="m-2"
          placeholder="Select Table"
          size="large"
          @change="getMysqColumn"
        >
          <el-option
            v-for="item in mysqlstore.tableList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 配置条件 -->
      <el-form-item label="检索条件">
        <el-col :span="8">
          <el-select
            v-model="whereClauseSelectColumn"
            class="m-2"
            placeholder="Select Table Columns"
            size="small"
          >
            <el-option
              v-for="item in tableColumns"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-select
            v-model="whereClauseSelectCondition"
            class="m-2"
            placeholder="Select Table Columns"
            size="small"
          >
            <el-option
              v-for="item in whereCondition"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="whereClauseSelectValue"
            style="width: 240px"
            placeholder="Please input"
            size="small"
          />
        </el-col>
      </el-form-item>

      <!-- 增加多个条件 -->
      <el-form-item
        v-for="(condition, index) in form.conditions"
        :key="condition.key"
        :label="'Condition' + index"
        :prop="'condition.' + index + '.value'"
      >
      <!-- and / or  -->
        <el-col :span="5">
          <el-select
            v-model="condition.whereClauseSelectANDOR"
            class="m-2"
            size="small"
          >
            <el-option
              v-for="item in ['AND', 'OR']"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-col>
        <!-- column name -->
        <el-col :span="5">
          <el-select
            v-model="condition.whereClauseSelectColumn"
            class="m-2"
            size="small"
          >
            <el-option
              v-for="item in tableColumns"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-col>
         <!-- column condition -->
         <el-col :span="5">
          <el-select
            v-model="condition.whereClauseSelectCondition"
            class="m-2"
            size="small"
          >
            <el-option
              v-for="item in whereCondition"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-col>
         <!-- column value -->
         <el-col :span="5">
          <el-input v-model="condition.whereClauseSelectValue" class="m-2" size="small"></el-input>
        </el-col>
        
        <el-button :span="4" class="mt-2" @click.prevent="removeCondition(condition)">
          Delete
        </el-button>
      </el-form-item>


      <el-form-item>
        <el-input
          v-model="currentSQL"
          autosize
          type="textarea"
          placeholder="SELECT * FROM ..."
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="addCondition">Add Condition</el-button>
        <el-button type="primary" @click="onGenSQL">GEN SQL</el-button>
        <el-button type="primary" @click="onSubmit">RUN SQL</el-button>
        <el-button type="primary" @click="onSaveCfg">SAVE CONFIG</el-button>
        <el-button>Cancel</el-button>
      </el-form-item>
    </el-form>

    <h2>执行结果展示</h2>

    <div>
      <el-input
          v-model="SQLresult"
          autosize
          type="textarea"
        />
    </div>


  </div>
</template>
  
  <script setup>
import axios from "../api/axios"; // 引入 Axios 封装
import { onMounted, reactive, ref } from "vue";
import { mysqlTableStore } from "../store/mytable";


const selectTable = ref("");  // 选择的表名
const whereClauseSelectColumn = ref("");  // where子句中选择的列名
const whereClauseSelectCondition = ref("");  // where子句中的条件
const whereClauseSelectValue = ref("");    // where子句中的值
const selectTableColumns = ref([]);   // select * 里面的列
const tableColumns = ref([]);   // mysql里面的table
const currentSQL = ref("");  // 当前的sql 
const mysqlstore = mysqlTableStore();  // 获取到mysqlTable
const whereCondition = ref([
  ">",
  "<",
  ">=",
  "<=",
  "=",
  "!=",
  "like",
  "not like",
  "in",
]);
// 所有的条件
const SQLresult = ref("")


const form = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
  conditions: []
});

function getMysqColumn(val) {
  console.log(val);
  try {
    axios
      .post("/get_mysql_columns", { table_name: val }) // key 后端接收的key，value前端的value
      .then((response) => {
        tableColumns.value = response.data.data;
        console.log(response);
      });
  } catch {
    (error) => {
      console.log(error);
    };
  }
}

function onGenSQL() {
  let columns_str = selectTableColumns.value
    .toString()
    .replace("[", "")
    .replace("]", "");
  console.log(form.conditions.value)

  currentSQL.value = `SELECT ${columns_str} FROM ${selectTable.value} 
WHERE ${whereClauseSelectColumn.value} ${whereClauseSelectCondition.value} ${whereClauseSelectValue.value} `;
}

function onSubmit() {
  console.log(currentSQL.value)
  try {
    axios
      .post("/run_sql", { sql: currentSQL.value }) // key 后端接收的key，value前端的value
      .then((response) => {
        console.log(response)
        SQLresult.value = response.data.data
      });
  } catch {
    (error) => {
      console.log(error);
    };
  }
}

function onSaveCfg() {}

function removeCondition(item) {
  const index = form.conditions.indexOf(item)
  if (index !== -1) {
    form.conditions.splice(index, 1)
  }
}

function addCondition() {
  
  form.conditions.push({
    key: Date.now(),
    value: '',
  })
  console.log(form.conditions)
}

onMounted(() => {});
</script>
  